<template>
  <div class="payment-container">
    <div class="payment-wrapper">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/products' }">商品列表</el-breadcrumb-item>
          <el-breadcrumb-item>支付确认</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <el-card class="payment-card" v-loading="loading">
        <template #header>
          <h2 class="payment-title">支付确认</h2>
        </template>

        <!-- 商品信息 -->
        <div class="product-info-section">
          <h3>商品信息</h3>
          <div class="product-summary">
            <el-image 
              :src="getProductImage()" 
              fit="cover" 
              class="product-image"
            />
            <div class="product-details">
              <h4 class="product-name">{{ productInfo.productName }}</h4>
              <div class="product-meta">
                <span class="seller">卖家：{{ sellerName }}</span>
                <span class="price">价格：¥{{ productInfo.price }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付信息 -->
        <div class="payment-info-section">
          <h3>支付信息</h3>
          <div class="payment-details">
            <div class="detail-item">
              <span class="label">商品价格：</span>
              <span class="value">¥{{ productInfo.price }}</span>
            </div>
            <div class="detail-item">
              <span class="label">运费：</span>
              <span class="value">¥0.00</span>
            </div>
            <div class="detail-item total">
              <span class="label">应付总额：</span>
              <span class="value">¥{{ productInfo.price }}</span>
            </div>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="payment-method-section">
          <h3>支付方式</h3>
          <div class="payment-methods">
            <el-radio-group v-model="paymentMethod">
              <el-radio label="alipay">
                <div class="payment-option">
                  <span class="payment-icon">💰</span>
                  <span>支付宝</span>
                </div>
              </el-radio>
              <el-radio label="wechat">
                <div class="payment-option">
                  <span class="payment-icon">💳</span>
                  <span>微信支付</span>
                </div>
              </el-radio>
              <el-radio label="bank">
                <div class="payment-option">
                  <span class="payment-icon">🏦</span>
                  <span>银行卡</span>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <el-button 
            type="primary" 
            size="large" 
            @click="handlePayment"
            :loading="paying"
            class="pay-button"
          >
            立即支付 ¥{{ productInfo.price }}
          </el-button>
          <el-button 
            size="large" 
            @click="handleCancel"
            class="cancel-button"
          >
            取消
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useProductStore } from '@/stores/product'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const productStore = useProductStore()

const loading = ref(false)
const paying = ref(false)
const paymentMethod = ref('alipay')
const sellerName = ref('未知用户')

// 商品信息
const productInfo = ref({
  productId: '',
  productName: '',
  price: 0,
  sellerId: ''
})

// 计算属性：获取商品图片
const getProductImage = () => {
  // 如果有商品详情，使用商品图片
  if (productDetail.value && productDetail.value.coverList) {
    return productDetail.value.coverList
  }
  // 否则使用占位图
  return '/placeholder.svg'
}

// 商品详情
const productDetail = ref<any>(null)

// 获取商品详情
const loadProductDetail = async () => {
  if (!productInfo.value.productId) return
  
  try {
    loading.value = true
    const result = await productStore.getProductDetail(Number(productInfo.value.productId))
    if (result) {
      productDetail.value = result
      // 更新商品信息
      productInfo.value.productName = result.name
      productInfo.value.price = result.price
      
      // 获取卖家信息
      if (result.userId) {
        try {
          const sellerInfo = await userStore.getUserById(result.userId)
          if (sellerInfo) {
            sellerName.value = sellerInfo.userName || sellerInfo.userAccount || '未知用户'
          }
        } catch (error) {
          console.error('获取卖家信息失败:', error)
        }
      }
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 处理支付
const handlePayment = async () => {
  try {
    paying.value = true
    
    // 确认支付
    await ElMessageBox.confirm(
      `确认使用${getPaymentMethodText()}支付 ¥${productInfo.value.price} 购买商品"${productInfo.value.productName}"吗？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 直接创建订单
    await createOrder()
    
    ElMessage.success('订单创建成功！')
    
    // 跳转到订单页面
    router.push('/user/orders')
    
  } catch (error: any) {
    if (error === 'cancel') {
      return
    }
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败，请重试')
  } finally {
    paying.value = false
  }
}

// 创建订单
const createOrder = async () => {
  try {
    const response = await request.post('/orders/add', null, {
      params: {
        productId: Number(productInfo.value.productId),
        userName: userStore.user!.username
      }
    })
    
    if (response.data) {
      console.log('订单创建成功:', response.data)
      return response.data
    } else {
      throw new Error(response.data?.message || '订单创建失败')
    }
  } catch (error: any) {
    console.error('创建订单失败:', error)
    throw error
  }
}

// 获取支付方式文本
const getPaymentMethodText = () => {
  switch (paymentMethod.value) {
    case 'alipay': return '支付宝'
    case 'wechat': return '微信支付'
    case 'bank': return '银行卡'
    default: return '支付宝'
  }
}

// 取消支付
const handleCancel = () => {
  router.back()
}

// 初始化
onMounted(() => {
  // 从路由参数获取商品信息
  const { productId, productName, price, sellerId } = route.query
  
  if (!productId || !productName || !price) {
    ElMessage.error('商品信息不完整')
    router.push('/products')
    return
  }
  
  productInfo.value = {
    productId: productId as string,
    productName: productName as string,
    price: Number(price),
    sellerId: sellerId as string
  }
  
  // 加载商品详情
  loadProductDetail()
})
</script>

<style scoped lang="scss">
.payment-container {
  padding: 32px 0;
  background: #f7f8fa;
  min-height: 100vh;
}

.payment-wrapper {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.payment-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  :deep(.el-card__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.payment-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
}

.product-info-section,
.payment-info-section,
.payment-method-section {
  margin-bottom: 30px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e8e8e8;
  }
}

.product-summary {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.product-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 14px;
  color: #666;
  
  .seller {
    color: #409eff;
  }
  
  .price {
    color: #e74c3c;
    font-weight: 600;
  }
}

.payment-details {
  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.total {
      font-size: 18px;
      font-weight: 600;
      color: #e74c3c;
      border-top: 2px solid #e8e8e8;
      padding-top: 16px;
      margin-top: 8px;
    }
    
    .label {
      color: #666;
    }
    
    .value {
      font-weight: 500;
      color: #2c3e50;
    }
  }
}

.payment-methods {
  .payment-option {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
  }
  
  .payment-icon {
    font-size: 20px;
  }
}

.payment-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.pay-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
  padding: 12px 32px;
  
  &:hover {
    background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }
}

.cancel-button {
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  color: #666;
  
  &:hover {
    background: #e6e6e6;
    border-color: #c0c0c0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-wrapper {
    padding: 0 15px;
  }
  
  .product-summary {
    flex-direction: column;
    text-align: center;
  }
  
  .payment-actions {
    flex-direction: column;
  }
  
  .pay-button,
  .cancel-button {
    width: 100%;
  }
}
</style>
